package com.xkp.news.servlet;

import com.xkp.news.entity.User;
import com.xkp.news.service.UserService;
import com.xkp.news.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/**
 * 处理用户登录请求的Servlet
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 //设置字符集
               req.setCharacterEncoding("utf-8");
               resp.setCharacterEncoding("utf-8");
               resp.setContentType("text/html;charset=utf-8");
               //获取用户传递的参数

       String acct= req.getParameter("userAcct");
       String pwd=req.getParameter("userPwd");


       //调用service的方法来判断用户是否能登录成功
        UserService userService=new UserServiceImpl();
        //根据用户账号去数据库中查询一个用户对象
        User user=userService.login(acct);
        if(user==null){
            //用户名不存在
            //resp.getWriter().write("<h1>用户名不存在</h1>");

            //跳转到登录页面 并显示提示信息
            resp.sendRedirect("index.html?a=1");
        }else{
            if(Objects.equals(user.getPwd(),pwd)){
                //登录成功
              //  resp.getWriter().write("<h1>登录成功</h1>");

                //获取session对象
                HttpSession session=req.getSession();
                //我们将登录的用户信息保存在session对象中
                session.setAttribute("user",user);

                resp.sendRedirect("main.html");
            }else{
                //登录失败
                //resp.getWriter().write("<h1>密码错误</h1>");

                resp.sendRedirect("index.html?a=2");
            }


        }




    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
